<?php

use Phalcon\Mvc\Controller;
use Phalcon\Mvc\View;

class ControllerBase extends Controller
{

    protected $_develop = array(
        'config' => ['index', 'config'],
        '',
    );

    /**
     * 单页记录条数，基类定义，其他继承的控制器按需重新赋值
     * @var int
     */
    public $pageSize = 20;

    /**
     * 当前登录用户信息
     * @var null
     */
    protected $currentLoginUser = null;

    /**
     * Json响应数据
     * @var array
     */
    protected $jsonResponseData = array(
        'code' => 0,
        'msg'  => '',
        'data' => null,
    );

    protected $queueTest;

    protected $queueBeta;

    protected $queueFormal;

    /**
     * 当类被创建时执行
     */
    public function onConstruct()
    {
    }

    /**
     * 基类初始化，获得登陆用户、导航、目录结构等信息
     */
    public function initialize()
    {
        $controller = $this->dispatcher->getControllerName();
        $action     = $this->dispatcher->getActionName();
        $uri        = "/{$controller}/{$action}";
        $this->view->setVar("curLink", $uri);
        $currentLoginUser = '';
        if ($this->cookies->has('remember-me')) {
            //Get the cookie
            $rememberMe = $this->cookies->get('remember-me');

            //Get the cookie's value
            $currentLoginUser = trim($rememberMe->getValue());
        } else {
            // return $this->response->redirect('index/pLogin');
        }
        $this->view->setVar('currentLoginUser', $currentLoginUser);
        $this->view->setVar('isAdministrator', 1);
        \Phalcon\Tag::setTitle($this->config->title);
    }

    /**
     * 弹出提示窗后跳转页面
     * @param string $alterMsg
     * @param string $jumpUrl
     * @param int $time
     */
    public function goPageAfterAlert($alterMsg, $jumpUrl = '/', $time = 3)
    {
        $this->view->setVar('alterMsg', $alterMsg);
        $this->view->setVar('jumpUrl', $jumpUrl);
        $this->view->setVar('time', $time);
        // $this->view->pick('pAlter');
        $this->view->render('public', 'pAlter');
    }

    /**
     * 弹出提示窗后跳转页面
     * @param string $alterMsg
     * @param string $jumpUrl
     * @param int $time
     */
    public function goPageAlert($alterMsg, $jumpUrl = '/', $time = 3)
    {
        $this->view->setVar('alterMsg', $alterMsg);
        $this->view->setVar('jumpUrl', $jumpUrl);
        $this->view->setVar('time', $time);
        $this->view->pick('pAlter');
        //$this->view->render('public', 'pAlter');
    }

    public function goPageAfterAlertNew($alterMsg, $msg, $jumpUrl = '/', $time = 3)
    {
        $this->view->setVar('alterMsg', $alterMsg);
        $this->view->setVar('msg', $msg);
        $this->view->setVar('jumpUrl', $jumpUrl);
        $this->view->setVar('time', $time);
        $this->view->render('public', 'pAlterNew');
    }

    /**
     * 输出 Json 格式的成功信息
     * @param $data
     * @param string $msg
     * @param int $code
     */
    public function outputJsonSuccess($data, $msg = "", $code = 0)
    {
        $this->jsonResponseData['data'] = $data;
        if ($msg != "") {
            $this->jsonResponseData['msg'] = $msg;
        }
        if ($code != 0) {
            $this->jsonResponseData['code'] = $code;
        }
        $this->outputJson();
    }

    /**
     * 输出 Json 格式的错误信息
     * @param $msg
     * @param $code
     * @param null $data
     */
    public function outputJsonError($msg, $code = -1, $data = null)
    {
        $this->jsonResponseData['msg']  = $msg;
        $this->jsonResponseData['code'] = $code;
        if ($data != null) {
            $this->jsonResponseData['data'] = $data;
        }
        $this->outputJson();
    }

    /**
     * 输出Json格式的返回信息
     * @param null $json
     */
    public function outputJson($json = null)
    {
        if ($json != null && is_array($json)) {
            $this->jsonResponseData = $json;
        }
        echo json_encode($this->jsonResponseData);
        $this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_NO_RENDER);
    }

    /**
     * 输出Jsonp格式的返回信息
     * @param null $json
     * @param string $callback
     */
    public function outputJsonp($json = null, $callback = 'callback', $domain = '')
    {
        if ($json != null && is_array($json)) {
            $this->jsonResponseData = $json;
        }
        echo '<script type="text/javascript">';
        //跨域 配置
        if (!empty($domain)) {
            echo 'document.domain="' . $domain . '";';
        }
        echo 'window.parent.' . $callback . '(' . json_encode($this->jsonResponseData) . ');';
        echo '</script>';
        $this->view->setRenderLevel(\Phalcon\Mvc\View::LEVEL_NO_RENDER);
    }

    public static function array_column($input, $columnKey, $indexKey = null)
    {
        $result = array();

        if (!is_array($input)) {
            return $result;
        }

        $isFetchAll = false;
        foreach ($input as $item) {
            if (is_array($columnKey)) {
                if (empty($columnKey)) {
                    $isFetchAll = true;
                }

                if (!empty($columnKey) || $isFetchAll) {
                    $tempItem = '';
                    if (!$isFetchAll) {
                        foreach ($columnKey as $colKey) {
                            if (isset($item[$colKey])) {
                                $tempItem[$colKey] = $item[$colKey];
                            }

                        }
                    } else {
                        $tempItem = $item;
                    }

                    if (null !== $indexKey && isset($item[$indexKey]) && !is_array($item[$indexKey])) {
                        $result[$item[$indexKey]] = $tempItem;
                    } else {
                        $result[] = $tempItem;
                    }

                }
            } else // 整数、字符串
            {
                if (isset($item[$columnKey])) {
                    if (null !== $indexKey && isset($item[$indexKey]) && !is_array($item[$indexKey])) {
                        $result[$item[$indexKey]] = $item[$columnKey];
                    } else {
                        $result[] = $item[$columnKey];
                    }

                }
            }
        }
        return $result;
    }

    /**
     * open接口, post获取数据
     * @param  [type] $url    [description]
     * @param  array  $args   [description]
     * @param  string $domain [description]
     * @return [type]         [description]
     */
    protected function _postData($url, $args = [], $domain = '')
    {
        return $this->_requestOpen($url, $args, $domain, 'post');
    }

    protected function _getData($url, $args = [], $domain = '')
    {
        return $this->_requestOpen($url, $args, $domain, 'get');
    }

    protected function _requestOpen($url, $args = [], $domain = '', $method = 'post')
    {
        // $args['access_token'] = $this->_getToken();
        if ($domain) {
            $url = $domain . $url;
        }
        $client = new \Util\RestClient();
        // var_dump($url . '?' . http_build_query($args, '', '&'));die();
        if ($method == 'post') {
            $data = $client->post(http_build_query($args, '', '&'), $url);
        } else {
            $data = $client->get($url . '?' . http_build_query($args, '', '&'));
        }
        if (json_decode($data)) {
            $result = json_decode($data, true);
        } else {
            $result = ["code" => -1, "msg" => "json 格式错误", "data" => []];
        }

        return $result;
    }

    protected function getUrl($type)
    {
        $url = '';
        switch ($type) {
            case '1':
                $url = $this->config->test_url;
                break;
            case '2':
                $url = $this->config->beta_url;
                break;
            case '3':
                $url = $this->config->formal_url;
                break;
            case '4':
                $url = $this->config->formal_file_xidi;
                break;
            case '5':
                $url = $this->config->formal_file_fenxiao;
                break;
            case '6':
                $url = $this->config->formal_file_zhaoshang;
                break;
            case '7':
                $url = $this->config->formal_crontab_xidi;
                break;
            case '8':
                $url = $this->config->formal_crontab_fenxiao;
                break;
            case '9':
                $url = $this->config->formal_quque_url;
                break;
        }
        return $url;
    }
}
